import logging
import math
from typing import Optional, List

from fastapi import APIRouter, Depends, Query, Path
from pydantic import Field, BaseModel
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

my_class_router = APIRouter(prefix="/school/tsClass", tags=["班级管理"], dependencies=[Depends(oauth2_scheme)])


class ClassQuerySearch(PaginationBase):
    # 筛选条件
    fclassname: Optional[str] = Field("", description="班级名称(支持前缀匹配)")
    fclassno: Optional[str] = Field("", description="班级编号")
    fsiteNo: Optional[str] = Field("", description="站点编号")


@my_class_router.get("/list", summary="班级查询接口")
def list_my_life(search: ClassQuerySearch = Query(), db: Session = Depends(get_db)):
    param = {}
    sql = "select  count(1) from a_ts_class where 1=1"
    if search.fsiteNo != "":
        sql = sql + " and fsite_no = :fsiteNo "
        param["fsiteNo"] = search.fsiteNo
    if search.fclassno != "":
        sql = sql + " and fclass_no = :fclassno "
        param["fclassno"] = search.fclassno
    if search.fclassname != "":
        sql = sql + " and fclass_name like concat('%', :fclassname ,'%')"
        param["fclassname"] = search.fclassname
    count = db.execute(text(sql), param).scalar()

    param = {}
    sql = "select fclass_no,fclass_name,fsite_no,fpoint_no,fimage,fperson,flayer_state,fupddate,foperator"
    sql = sql + " from a_ts_class where 1=1"
    if search.fsiteNo != "":
        sql = sql + " and fsite_no = :fsiteNo "
        param["fsiteNo"] = search.fsiteNo
    if search.fclassno != "":
        sql = sql + " and fclass_no = :fclassno "
        param["fclassno"] = search.fclassno
    if search.fclassname != "":
        sql = sql + " and fclass_name like concat('%', :fclassname ,'%')"
        param["fclassname"] = search.fclassname
    if search.order == "desc":
        sql = sql + " order by  fclass_no desc "
    else:
        sql = sql + " order by  fclass_no "
    sql = sql + " limit :limit offset :offset "
    param["offset"] = search.offset
    param["limit"] = search.limit
    data = db.execute(text(sql), param).fetchall()

    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['fclassno'] = data[key][0]
        d1['fclassname'] = data[key][1]
        d1['fsiteno'] = data[key][2]
        d1['fpointno'] = data[key][3]
        d1['fimage'] = data[key][4]
        d1['fperson'] = data[key][5]
        d1['flayerstate'] = data[key][6]
        d1['fupddate'] = data[key][7]
        d1['foperator'] = data[key][8]
        data_list.append(d1)

    info_dict = {"list": data_list,
                 "limit": search.limit,
                 "page": search.pageIndex,
                 "pages": (count + search.limit - 1) // search.limit,
                 "total": count}
    return BaseResponse.success(data=info_dict)


class ClassCreate(BaseModel):
    """班级资料新增请求参数"""
    fclassno: str = Field(..., description="班级编号")
    fclassname: str = Field(..., description="班级名称")
    fsiteno: str = Field(..., description="站点编号")
    fpointno: str = Field(..., description="监测点编号")
    flayerstate: int = Field(..., description="班级状态")
    fupddate: str = Field(..., description="更新日期(格式需与数据库存储一致)")
    fperson: Optional[str] = Field("", description="负责人，默认为空")
    fimage: Optional[str] = Field("", description="班级图片路径，默认为空")


@my_class_router.post("/create", summary="班级资料新增接口")
def create_my_class(create: ClassCreate, db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)):
    try:
        fclassno = create.fclassno
        user_id = EncryptionMiddleware.get_current_user(token)
        with db.begin():
            sql = "select 1 from a_ts_class where fclass_no= :fclassno "
            data = db.execute(text(sql), {"fclassno": fclassno}).fetchall()

            if len(data) > 0:
                return BaseResponse.error(message="班级已存在")
            else:

                sql = "insert into a_ts_class(fclass_no,fclass_name,fsite_no,fpoint_no,fimage,fperson,flayer_state,fupddate,foperator)"
                sql = sql + " values( :fclassno , :fclassname , :fsiteno , :fpointno , :fimage , :fperson , :flayerstate ,now(), :userid );"
                db.execute(text(sql), {
                    "fclassno": fclassno,
                    "fclassname": create.fclassname,
                    "fpointno": create.fpointno,
                    "fimage": create.fimage,
                    "fperson": create.fperson,
                    "flayerstate": create.flayerstate,
                    "userid": user_id,
                })
                data = {"fclassno": fclassno
                    , "fclassname": create.fclassname
                    , "fsiteno": create.fsiteno
                    , "fpointno": create.fpointno
                    , "fperson": create.fperson
                    , "fimage": create.fimage
                    , "flayerstate": create.flayerstate
                    , "fupddate": create.fupddate
                    , "foperator": user_id
                        }
                return BaseResponse.success()

    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@my_class_router.post("/update", summary="班级修改接口")
def update_my_class(update: ClassCreate, db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)):
    try:
        user_id = EncryptionMiddleware.get_current_user(token)
        with db.begin():
            sql = "update a_ts_class"
            sql = sql + " set fclass_name= :fclassname ,fsite_no= :fsiteno "
            sql = sql + ",fpoint_no= :fpointno ,fimage= :fimage ,fperson= :fperson "
            sql = sql + ",flayer_state= :flayerstate ,fupddate=now(),foperator= :userid "
            sql = sql + " where fclass_no= :fclassno "
            db.execute(text(sql), {
                "fclassname": update.fclassname,
                "fsiteno": update.fsiteno,
                "fpointno": update.fpointno,
                "fimage": update.fimage,
                "fperson": update.fperson,
                "flayerstate": update.flayerstate,
                "userid": user_id,
                "fclassno": update.fclassno,
            })
            return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@my_class_router.post("/delete/{fclassno}", summary="班级删除接口")
def delete_my_class(fclassno: str = Path(description="班级编号"), db: Session = Depends(get_db),
                    token: str = Depends(oauth2_scheme)):
    try:
        with db.begin():
            sql = "delete from a_ts_class where fclass_no= :fclassno "
            db.execute(text(sql), {
                "fclassno": fclassno
            })
            return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")
